package de.hauck.rtmidlet;

import java.io.IOException;
import java.io.InputStream;
import java.util.Vector;

import javax.microedition.io.Connector;
import javax.microedition.io.HttpConnection;

//import org.microemu.log.Logger;

import de.hauck.rtmidlet.model.Configuration;
import de.hauck.rtmidlet.model.StockBean;
import de.hauck.rtmidlet.model.YahooBean;
import de.hauck.rtmidlet.utils.MyLogger;
import de.hauck.rtmidlet.views.CanvasYahoo;

public class DownloadYahooThread implements Runnable {
	/*
	 * parameters for Yahoo-Download Symbol s Name n Date d1 Time t1 Last Trade
	 * l1 Bid b Ask a Open o Day's High h Day's Low g Previous Close p Change &
	 * Percent c Change c1 Volume v Average Daily Volume a2 Day's Range m
	 * 52-week Range w Earnings/Share e P/E Ratio r Dividend Pay Date r1
	 * Ex-Dividend Date q Dividend/Share d Dividend Yield y Market
	 * Capitalization j1 Time (Real Time) t5 Last Trade (Real Time) l9 Change
	 * (Real Time) c6 Change % (Real Time) p4 Bid (Real Time) b1 Ask (Real Time)
	 * a3
	 */

	private Configuration c;
	private CanvasYahoo _yahooCanvas;
	private String _url, _urlIndices;
	private String params = "&f=sl1d1t1c1p4ohgv";
	
	public DownloadYahooThread(CanvasYahoo yahooCanvas, Vector stocksVec,
			String url) {
		_yahooCanvas = yahooCanvas;
		_url = url;
		_urlIndices=url;
		String name="";
		for (int i = 0; i < stocksVec.size(); i++) {
			name=((StockBean) stocksVec.elementAt(i)).getSymbolYahoo();
			if (name.equals("")) name="DUMMY";
			_url += name + ",";
		}
		_url += params;
		_urlIndices+="%5EGDAXI,%5ETECDAX,%5EDJI,%5ENDX,%5EGSPC" + params;
		new Thread(this).start();
	}

	public void run() {
		downloadYahoo();
		downloadYahooIndices();
	}
	
	private void downloadYahoo() {
		InputStream is = null;
		try {
			HttpConnection hc = (HttpConnection) Connector.open(_url);
			if (hc != null) {
				is = hc.openInputStream();
				_yahooCanvas.updateStatus(c.CONN_STATUS_CONNECTING);
				int ch; // Check the Content-Length first
				long length = hc.getLength();
				c.addToDownloadCounter(length);
				String yahooString = "";
				if (length != -1) {
					_yahooCanvas.updateStatus(c.CONN_STATUS_CONNECTED);
					for (int i = 0; i < length; i++)
						if ((ch = is.read()) != -1)
							yahooString += ((char) ch);
				} else {
					// if the content-length is not available
					while ((ch = is.read()) != -1)
						yahooString += ((char) ch);

				}
				is.close();
				hc.close();
				System.out.println(yahooString);
				_yahooCanvas.updateStatus(c.CONN_STATUS_OFFLINE);
				_yahooCanvas
						.updateYahooBean(convertString2YahooBeanVector(yahooString));
			}
		} catch (IOException e) {
			e.printStackTrace();
			RTMidlet.getInstance().setCurrent(_yahooCanvas);
			RTMidlet.getInstance().alert("Error", e.getMessage(), Configuration.ALERT_WAIT_TIME);
		} catch (Exception e) {
			e.printStackTrace();
			RTMidlet.getInstance().setCurrent(_yahooCanvas);
			RTMidlet.getInstance().alert("Error", e.getMessage(), Configuration.ALERT_WAIT_TIME);
		}
	}
	
	private void downloadYahooIndices() {
		InputStream is = null;
		try {
			HttpConnection hc = (HttpConnection) Connector.open(_urlIndices);
			if (hc != null) {
				is = hc.openInputStream();
				_yahooCanvas.updateStatus(c.CONN_STATUS_CONNECTING);
				int ch; // Check the Content-Length first
				long length = hc.getLength();
				c.addToDownloadCounter(length);
				String yahooString = "";
				if (length != -1) {
					_yahooCanvas.updateStatus(c.CONN_STATUS_CONNECTED);
					for (int i = 0; i < length; i++)
						if ((ch = is.read()) != -1)
							yahooString += ((char) ch);
				} else {
					// if the content-length is not available
					while ((ch = is.read()) != -1)
						yahooString += ((char) ch);

				}
				is.close();
				hc.close();
				MyLogger.debug(yahooString);
				_yahooCanvas.updateStatus(c.CONN_STATUS_OFFLINE);
				_yahooCanvas
						.updateIndicesYahooBean(convertString2YahooBeanVector(yahooString));
			}
		} catch (IOException e) {
			e.printStackTrace();
			RTMidlet.getInstance().setCurrent(_yahooCanvas);
			RTMidlet.getInstance().alert("Error", e.getMessage(), Configuration.ALERT_WAIT_TIME);
		} catch (Exception e) {
			e.printStackTrace();
			RTMidlet.getInstance().setCurrent(_yahooCanvas);
			RTMidlet.getInstance().alert("Error", e.getMessage(), Configuration.ALERT_WAIT_TIME);
		}

	}

	
	private Vector convertString2YahooBeanVector(String str) {
		// No StringTokenizer in J2ME, parsing strings with this method
		YahooBean yb = new YahooBean();
		Vector ybVec = new Vector();
		int offset = 0;
		int counter = 0;
		for (int i = 0; i < str.length(); i++) {
			if (str.charAt(i) == ',') {
				String token = str.substring(offset, i);
				yb.setToken(counter, token);
				counter++;
				offset = i + 1;
			} else if (str.charAt(i) == '\n') {
				String token = str.substring(offset, i - 1);
				yb.setToken(counter, token);
				ybVec.addElement(yb);
				counter = 0;
				offset = i + 1;
				yb.printBean();
				yb = new YahooBean();
			}
		}
		MyLogger.debug("YB converted - size : "+ybVec.size());
		return ybVec;
	}
}
